package org.luo.lan.server.initializers;

import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.serialization.ObjectDecoder;
import io.netty.handler.codec.serialization.ObjectEncoder;
import io.netty.handler.ssl.SslHandler;
import org.luo.lan.common.config.SslConfig;
import org.luo.lan.common.util.SslEngineUtil;
import org.luo.lan.server.config.ServerConfig;
import org.luo.lan.server.handlers.ServerBridgeHandler;

import javax.net.ssl.SSLEngine;

public class BridgeServerInitializers extends ChannelInitializer<SocketChannel> {
    @Override
    public void initChannel(SocketChannel ch) {
        ChannelPipeline pipeline = ch.pipeline();
        SslConfig sslConfig = SslConfig.builder(ServerConfig.getInstance().getSslPwd(), ServerConfig.getInstance().getSslFileName())
                .useClientMode(false).needClientAuth(true).build();

        SSLEngine engine = SslEngineUtil.getSslEngine(sslConfig);
        pipeline.addLast("ssl", new SslHandler(engine));
        ch.pipeline().addLast(new ObjectEncoder());
        ch.pipeline().addLast(new ObjectDecoder((className) -> Class.forName(className)));
        pipeline.addLast(new ServerBridgeHandler());
    }
}
